package tech.popsoft.cip.manage.service.impl;

import org.springframework.stereotype.Service;
import tech.popsoft.cip.manage.service.ApiServiceLogService;
import tech.popsoft.platform.common.base.BaseServiceImpl;
import tech.popsoft.platform.common.utils.DateUtils;
import tech.popsoft.cip.api.entity.ApiRequest;
import tech.popsoft.cip.api.entity.ApiResponse;
import tech.popsoft.cip.manage.entity.ApiServiceLog;
import tech.popsoft.cip.manage.mapper.ApiServiceLogMapper;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 服务日志 服务实现类
 * @author wqliu
 * @date 2021-08-17
 *
 */
@Service
public class ApiServiceLogServiceImpl extends BaseServiceImpl<ApiServiceLogMapper, ApiServiceLog> implements ApiServiceLogService {
    @Override
    public ApiServiceLog init() {
        ApiServiceLog entity=new ApiServiceLog();

        return entity;
    }

    @Override
    public void recordLog(ApiRequest request, ApiResponse response, LocalDateTime receiveTime) {

        LocalDateTime responseTime = LocalDateTime.now();
        ApiServiceLog apiServiceLog = new ApiServiceLog();
            apiServiceLog.setAppCode(request.getAppCode());
            apiServiceLog.setServiceCode(request.getServiceCode());
            apiServiceLog.setRequestTime(DateUtils.toLocalDateTime(request.getRequestTime()));
            apiServiceLog.setReceiveTime(receiveTime);
            apiServiceLog.setRequestBusinessData(request.getData());
            apiServiceLog.setExecuteResult(response.getExecuteResult());
            apiServiceLog.setErrorCode(response.getErrorCode());
            apiServiceLog.setErrorMessage(response.getErrorMessage());
            apiServiceLog.setResponseTime(responseTime);
            apiServiceLog.setResponseBusinessData(response.getData());
            //计算执行时间
            apiServiceLog.setExecutionTime(Duration.between(receiveTime, responseTime).toMillis());
            //保存
            add(apiServiceLog);

    }
}
